package com.kaikeba.t31.service.impl;

import com.kaikeba.t31.admin.po.AdminRole;
import com.kaikeba.t31.admin.po.AdminUser;
import com.kaikeba.t31.core.service.impl.CrudServiceImpl;
import com.kaikeba.t31.dao.AdminUserMapper;
import com.kaikeba.t31.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yumingzhi
 * @since 2021-11-14
 */
@Service
public class AdminUserServiceImpl extends CrudServiceImpl<AdminUser> implements AdminUserService {

    @Resource
    private AdminUserMapper adminUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    @Transactional(readOnly = true)
    public boolean saveOrUpdate(AdminUser entity) {
        // 添加时，设置lock=false
        if (null == entity.getId()) {
            entity.setLockout(false);
        }

        // 加密MD5（MD5(password, salt))
        entity.setPassword(passwordEncoder.encode(entity.getPassword()));
//         passwordHelper.encryPassword(entity);

        boolean result = super.saveOrUpdate(entity);
        ((AdminUserMapper) getBaseMapper()).deleteRoleByUser(entity.getId());

        Long[] roleIds = entity.getRoleIds();
        if (null != roleIds) {
            for (Long roleId : roleIds) {
                ((AdminUserMapper) getBaseMapper()).insertRoleAndUser(roleId, entity.getId());
                //TODO: 待补充和完善下面的代码
            }
        }

        return result;
    }

    @Override
    public List<AdminRole> selectRoleByUser(Long id) {
        return ((AdminUserMapper) getBaseMapper()).selectRoleByUser(id);
    }

    @Override
    public int lock(Long id) {
        return adminUserMapper.lock(id);
    }

    @Override
    public AdminUser getByName(String name) {
        return adminUserMapper.getByName(name);
    }

//    @Override
//    public boolean saveOrUpdate(AdminUser adminUser) {
//        if (adminUser.getId() == null) {
//            adminUserMapper.insert(adminUser);
//        } else {
//            adminUserMapper.updateById(adminUser);
//        }
//        return true;
//    }

    @Override
    public List<AdminUser> list(AdminUser entity) {
        return adminUserMapper.selectList(entity);
    }
}
